package org.freespace.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;

public class DateUtil {
    public static final String yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
    public static final String yyyyMMdd = "yyyy-MM-dd";
    public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    public static long utcToTs(String utcStr){
        try {
            Date date = null;
            long ts = 0;
            if (utcStr.contains("+08:00")) {
                try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'+08:00");
                    date = df.parse(utcStr);
                } catch (Exception e) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+08:00");
                    date = df.parse(utcStr);
                }

                ts = stringToTS(dateToString(date, "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss");
            } else {
                try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'+8:00");
                    df.setTimeZone(TimeZone.getTimeZone("UTC"));
                    date = df.parse(utcStr + "+08:00");
                } catch (Exception e) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'+08:00");
                    df.setTimeZone(TimeZone.getTimeZone("UTC"));
                    date = df.parse(utcStr + "+08:00");
                }

                ts = stringToTS(dateToString(date, "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss");
            }
            return ts;
        }catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static String dateToString(Date date, String format) {
        DateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }

    public static Long stringToTS(String dateStr, String format) throws ParseException {
        DateFormat df = new SimpleDateFormat(format);
        long date = df.parse(dateStr).getTime();
        return date;
    }

    public static String timestampToString(long timestamp) {
        return timestampToDateString(timestamp, "yyyy-MM-dd HH:mm:ss");
    }

    public static String timestampToDateString(long timestamp, String format) {
        Timestamp ts = new Timestamp(timestamp);
        DateFormat df = new SimpleDateFormat(format);
        return df.format(ts);
    }

    public static String timestampToHourDateString(long timestamp) {
        return timestampToDateString(timestamp, "HH:mm:ss");
    }
}
